#include "log.hpp"
#include "socket.hpp"
#include "nocpy.hpp"

#include <assert.h>

#include <sys/epoll.h>

class epoller : public nocpy
{
public:
    epoller()
    {
        _ep = epoll_create(128);
        assert(_ep > 0);
    }

    int epollWait(epoll_event events[], int num){
        int n = epoll_wait(_ep, events, num, _timeout);
        if(n < 0){
            ls(Warning, "epollWait error, code: %d, errno: %s", errno, strerror(errno));
            return -1;
        }
        return n;
    }

    bool epollCtl(int op, int sock, uint32_t event){
        int n = 0;
        if(op == EPOLL_CTL_DEL){
            n = epoll_ctl(_ep, op, sock, nullptr);
            if(n < 0){
                ls(Warning, "epoll_ctl_del error, code: %d, errno: %s", errno, strerror(errno));
                return false;
            }
        }
        else{
            epoll_event ee;
            ee.events = event;
            ee.data.fd = sock;
            n = epoll_ctl(_ep, op, sock, &ee);
            if(n < 0){
                ls(Warning, "epoll_ctl_updata error, code: %d, errno: %s", errno, strerror(errno));
                return false;
            }
        }
        return true;;
    }


    ~epoller(){
        close(_ep);
    }

private:
    int _ep;
    int _timeout = 3000;
};